const Controller = require('egg').Controller;

class AdminController extends Controller {
    // 获取验证码
    async captcha() {
        const { ctx, service } = this;

        try {
            const captcha = await service.admin.generateCaptcha();
            ctx.body = {
                code: 0,
                data: captcha,
                msg: '获取验证码成功'
            };
        } catch (error) {
            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取验证码失败'
            };
        }
    }

    // 管理员登录 
    async login() {
        const { ctx, service } = this;

        try {
            // 参数验证 
            const rules = {
                email: { type: 'string', required: true },
                password: { type: 'string', required: true },
                captcha: { type: 'string', required: true },
                captchaId: { type: 'string', required: true }
            };
            ctx.validate(rules);

            const loginData = ctx.request.body;

            // 验证验证码
            await service.admin.verifyCaptcha(loginData.captchaId, loginData.captcha);

            const result = await service.admin.login(loginData);

            ctx.body = {
                code: 0,
                data: result,
                msg: '登录成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '登录失败'
            };
        }
    }
    // 创建管理员
    async create() {
        const { ctx, service } = this;

        try {
            // 参数验证
            const rules = {
                admin_name: { type: 'string', required: true },
                email: { type: 'string', required: true },
                password: { type: 'string', required: true }
            };
            ctx.validate(rules);

            const adminData = ctx.request.body;
            const result = await service.admin.create(adminData);

            ctx.body = {
                code: 0,
                data: result,
                msg: '创建成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '创建管理员失败'
            };
        }
    }

    // 获取管理员列表
    async list() {
        const { ctx, service } = this;

        try {
            const query = ctx.query;
            const result = await service.admin.getAdmins(query);

            ctx.body = {
                code: 0,
                data: result,
                msg: '获取成功'
            };
        } catch (error) {
            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取管理员列表失败'
            };
        }
    }

    // 获取管理员详情
    async detail() {
        const { ctx, service } = this;

        try {
            const { id } = ctx.params;

            // 验证ID参数
            const rules = {
                id: { type: 'string', required: true }
            };
            ctx.validate(rules, ctx.params);

            const admin = await service.admin.getAdminById(id);

            ctx.body = {
                code: 0,
                data: admin,
                msg: '获取成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取管理员详情失败'
            };
        }
    }

    // 更新管理员信息
    async update() {
        const { ctx, service } = this;

        try {
            const { id } = ctx.params;
            const updateData = ctx.request.body;

            // 验证路径参数
            const paramRules = {
                id: { type: 'string', required: true }
            };
            ctx.validate(paramRules, ctx.params);

            // 验证body参数
            const bodyRules = {
                admin_name: { type: 'string', required: false },
                email: { type: 'string', required: false },
            };
            ctx.validate(bodyRules);

            // 不允许更新密码（单独接口处理）
            if (updateData.password) {
                throw new Error('请使用修改密码接口');
            }

            const result = await service.admin.updateAdmin(id, updateData);

            ctx.body = {
                code: 0,
                data: result,
                msg: '更新成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '更新管理员信息失败'
            };
        }
    }

    // 删除管理员
    async delete() {
        const { ctx, service } = this;

        try {
            const { id } = ctx.params;

            // 验证ID参数
            const rules = {
                id: { type: 'string', required: true }
            };
            ctx.validate(rules, ctx.params);

            await service.admin.deleteAdmin(id);

            ctx.body = {
                code: 0,
                data: null,
                msg: '删除成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '删除管理员失败'
            };
        }
    }

    // 获取当前登录管理员信息
    async current() {
        const { ctx, service } = this;

        try {
            // 从token中获取管理员ID
            const token = ctx.request.header.admintoken;
            const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);

            // 验证是否为管理员token
            if (decode.type !== 'admin') {
                throw new Error('无权限访问');
            }

            const admin = await service.admin.getCurrentAdmin(decode.admin_id);

            ctx.body = {
                code: 0,
                data: admin,
                msg: '获取成功'
            };
        } catch (error) {
            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取管理员信息失败'
            };
        }
    }

    // 修改密码
    async changePassword() {
        const { ctx, service } = this;

        try {
            const rules = {
                oldPassword: { type: 'string', required: true },
                newPassword: { type: 'string', required: true }
            };
            ctx.validate(rules);

            const { oldPassword, newPassword } = ctx.request.body;

            // 从token中获取管理员ID
            const token = ctx.request.header.admintoken;
            const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);

            // 验证是否为管理员token
            if (decode.type !== 'admin') {
                throw new Error('无权限访问');
            }

            await service.admin.changePassword(decode.admin_id, {
                oldPassword,
                newPassword
            });

            ctx.body = {
                code: 0,
                data: null,
                msg: '密码修改成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '修改密码失败'
            };
        }
    }
    // 修改管理员密码（管理员管理接口）
    async changeAdminPassword() {
        const { ctx, service } = this;

        try {
            const rules = {
                admin_id: { type: 'integer', required: true },
                old_password: { type: 'string', required: true },
                new_password: { type: 'string', required: true }
            };
            ctx.validate(rules);

            const { admin_id, old_password, new_password } = ctx.request.body;

            await service.admin.changeAdminPassword(admin_id, {
                oldPassword: old_password,
                newPassword: new_password
            });

            ctx.body = {
                code: 0,
                data: null,
                msg: '密码修改成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '修改密码失败'
            };
        }
    }
    // 管理员登出
    async logout() {
        const { ctx, service } = this;

        try {
            // 从token中获取管理员ID（用于验证token有效性）
            const token = ctx.request.header.token;
            const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);

            // 验证是否为管理员token
            if (decode.type !== 'admin') {
                throw new Error('无权限访问');
            }

            // 调用服务层登出逻辑
            await service.admin.logout();

            ctx.body = {
                code: 0,
                data: null,
                msg: '登出成功'
            };
        } catch (error) {
            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '登出失败'
            };
        }
    }
}

module.exports = AdminController;